package com.project.config;

import com.project.Boot;
import com.project.Util.LocalDateChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author lyl
 * description:
 */
@Configuration
@ComponentScan(basePackageClasses = Boot.class)
@EnableWebMvc//提供mvc支持
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService converService = (GenericConversionService) initializer.getConversionService();
            converService.addConverter(new LocalDateChange());
        }
    }

    /**
     * 设置编码集，仅对get提交生效
     *
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringHttpMessageConverter stringHttpMessageConverter = (StringHttpMessageConverter) converters.get(1);
        stringHttpMessageConverter.setDefaultCharset(Charset.forName("utf-8"));
    }

    /**
     * 设置静态页面所在路径
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //方式以html开始的都在resource下static/html中寻找
        registry.addResourceHandler("/html/**").addResourceLocations("classpath:/static/html/");
    }
}
